package com.zhengjiang.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhengjiang
 * @version 1.0.0
 * @description
 * @date 2021/6/13
 **/
public class ThreadPoolTest {
    public static void main(String[] args) {
//        fixThreadPoolDemo();
        scheduledTheadPoolDemo();
    }

    static void scheduledTheadPoolDemo(){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        Runnable runnable = ()->{
            for (int i = 0;i<100;i++)
                System.out.println(Thread.currentThread().getName() + "线程的值" + i);
        };
        //指定的任务将在delay延迟后执行
//        scheduledExecutorService.schedule(runnable,5,TimeUnit.SECONDS);

        //指定的任务将在delay延迟后执行,并且以设定的频率重复执行
//        scheduledExecutorService.scheduleAtFixedRate(runnable,5,5,TimeUnit.SECONDS);

        //创建并执行一个在给定初始延迟后首次启用的定期操作，随后在每次执行终止和下次执行开始之间都存在给定的延迟。
        //如果任务在任一次执行时遇到异常，就会取消后续执行;
        scheduledExecutorService.scheduleWithFixedDelay(runnable,3,3,TimeUnit.SECONDS);
//        scheduledExecutorService.shutdown();
    }

    static void fixThreadPoolDemo(){
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Runnable runnable = ()->{
            for (int i = 0;i<100;i++)
                System.out.println(Thread.currentThread().getName() + "线程的值" + i);
        };
        executorService.submit(runnable);
        executorService.submit(runnable);
        executorService.shutdown();
    }
}
